var teacherStaffViewModel = new TeacherStaffViewModel();
function bodyOnLoad() {
	ko.applyBindings(teacherStaffViewModel);
}

//---------------------------------------------------------------------------------

function TeacherStaffViewModel() {
	var self = this;
	self.title = "Version New";
	self.windowMode = "";

	self.staffArr = ko.observableArray([]);
	self.label = ko.observable('dialog test');
	self.isOpen = ko.observable(false);
	self.currentContent = ko.observable();

	var periodPerSecData = $.getJSON(baseUrl + SM_GETPERIODPERSECTIONINACAD + currentAypId, {
		returnformat : 'json'
	}, function(allData1) {

		console.log("periodPerSecData---||---", allData1)

	})
	///

	//-----------------Loading subjectTitle JSON---------------------------------
	//baseUrl+SM_GETTEACHERUTILIZATION+currentAypId

	var tumContentJsonData = $.getJSON(baseUrl + SM_GETTEACHERUTILIZATION + currentAypId, {
		returnformat : 'json'
	}, function(allData1) {

		//  var tumContentJsonData              = $.getJSON('json/ts-1', {returnformat : 'json' }, function(allData1) {

		// var teacherData =  _.sortBy(allData1, 'teacherId');//,'sectionId','subjectId','classId'
		showLoader(true, TYPE_LOADING);

		var constructedTeacherJson = [];
		//Modified Json
		var teacherJsonObject;
		// Modified object
		var sectionJsonObject;
		var subjectJsonObject;
		var classJsonObject;

		var sectionJsonArr;
		var subjectJsonArr;
		var classJsonArr;

		//----------Getting Unique Values-------Start--------

		var tempIdArr = [];
		for (var i = 0; i < allData1.length; i++) {
			tempIdArr.push(allData1[i].teacherId);
		}
		var uniqueIdArr = _.uniq(tempIdArr);

		//----------Getting Unique Values-------End--------

		for (var j = 0; j < uniqueIdArr.length; j++) {
			teacherJsonObject = new Object();
			// Modified object
			var teacherIdArr = [];
			var sectionIdArr = [];
			var subjectIdArr = [];
			var classIdArr = [];

			for (var k = 0; k < allData1.length; k++) {
				if (allData1[k].teacherId == uniqueIdArr[j]) {
					var tempobj = new Object();
					tempobj.teacherId = allData1[k].teacherId;
					tempobj.sectionId = allData1[k].sectionId;
					tempobj.subjectId = allData1[k].subjectId;
					tempobj.classId = allData1[k].classId;

					tempobj.title = allData1[k].title;
					tempobj.name = allData1[k].name;
					tempobj.isClassTeacher = allData1[k].isClassTeacher;
					tempobj.sectionTitle = allData1[k].sectionTitle;
					tempobj.subjectTitle = allData1[k].subjectTitle;
					tempobj.classTitle = allData1[k].classTitle;

					tempobj.emailAddress = allData1[k].emailAddress;
					tempobj.contactNumber = allData1[k].contactNumber;
					tempobj.periodPerWeek = allData1[k].periodPerWeek;
					tempobj.cePeriodPerWeek = allData1[k].cePeriodPerWeek;
					tempobj.labPeriodPerWeek = allData1[k].labPeriodPerWeek;

					teacherJsonObject.title = allData1[k].title;
					teacherJsonObject.name = allData1[k].name;

					if (allData1[k].isClassTeacher) {
						teacherJsonObject.classTitle = allData1[k].classTitle;
						teacherJsonObject.isClassTeacher = allData1[k].isClassTeacher;
					} else {
					}

					console.log(k, " class ", allData1[k].classTitle, " name ", allData1[k].name, " isclassteacher ", allData1[k].isClassTeacher)

					teacherJsonObject.emailAddress = allData1[k].emailAddress;
					teacherJsonObject.contactNumber = allData1[k].contactNumber;
					teacherJsonObject.teacherId = allData1[k].teacherId;
					teacherJsonObject.periodPerWeek = allData1[k].periodPerWeek;
					teacherJsonObject.cePeriodPerWeek = allData1[k].cePeriodPerWeek;
					teacherJsonObject.labPeriodPerWeek = allData1[k].labPeriodPerWeek;
					sectionIdArr.push(allData1[k].sectionId)//selection ids for that group based on teacher id
					subjectIdArr.push(allData1[k].subjectId)//subjectId ids for that group based on teacher id
					classIdArr.push(allData1[k].classId)//classId ids for that group based on teacher id
					teacherIdArr.push(tempobj);
				}
			}
			var uniqueSectionIdArr = _.uniq(sectionIdArr);
			var uniqueSubjectIdArr = _.uniq(subjectIdArr);
			var uniqueClassIdArr = _.uniq(classIdArr);

			sectionJsonArr = [];

			//console.log("teacherIdArr",teacherIdArr,uniqueSectionIdArr)

			for (var s = 0; s < uniqueSectionIdArr.length; s++) {
				var subjectidGroupArr = [];
				subjectJsonArr = [];

				for ( t = 0; t < teacherIdArr.length; t++) {
					if (teacherIdArr[t].sectionId == uniqueSectionIdArr[s]) {
						classJsonArr = [];
						for (var u = 0; u < uniqueSubjectIdArr.length; u++) {
							if (teacherIdArr[t].subjectId == uniqueSubjectIdArr[u]) {
								//----------------------------------------------------
								sectionJsonObject = new Object()
								subjectJsonObject = new Object();
								for (var v = 0; v < uniqueClassIdArr.length; v++) {
									if (teacherIdArr[t].classId == uniqueClassIdArr[v]) {
										classJsonObject = new Object();
										classJsonObject.classId = teacherIdArr[t].classId
										classJsonObject.classTitle = teacherIdArr[t].classTitle
										classJsonArr.push(classJsonObject);
									}
								}
								subjectJsonObject.subjectId = teacherIdArr[t].subjectId
								subjectJsonObject.subjectTitle = teacherIdArr[t].subjectTitle

								subjectJsonObject.periodPerWeek = teacherIdArr[t].periodPerWeek
								subjectJsonObject.cePeriodPerWeek = teacherIdArr[t].cePeriodPerWeek
								subjectJsonObject.labPeriodPerWeek = teacherIdArr[t].labPeriodPerWeek

								subjectJsonObject.classDetail = classJsonArr;
								subjectJsonArr.push(subjectJsonObject);
								//----- -----------------------------------------------
								//console.log(t,"If  subjectTitle",s, subjectJsonArr )
							}
						}
						sectionJsonObject.sectionId = teacherIdArr[t].sectionId//main
						sectionJsonObject.sectionTitle = teacherIdArr[t].sectionTitle//main
					}
				}
				//console.log("-----------OUT-------------")
				sectionJsonObject.subject = subjectJsonArr//main
				sectionJsonArr.push(sectionJsonObject) //main
			}
			teacherJsonObject.section = sectionJsonArr;
			//main
			constructedTeacherJson.push(teacherJsonObject) //main
		}
		//console.log("constructedTeacherJson=======>",constructedTeacherJson)
		// var mappedContentData           = jQuery.map(allData1, function(item) {
		var mappedContentData = jQuery.map(constructedTeacherJson, function(item) {
			return new TeacherStaffVO(item, self.currentContent)

		});
		self.staffArr(mappedContentData);

		showLoader(false);

	});

	//------------------------------For Filtering Purpose ----------------------------

	ko.utils.stringStartsWith = function(string, startsWith) {
		string = string || "";
		if (startsWith.length > string.length)
			return false;
		return string.substring(0, startsWith.length) === startsWith;
	}, self.nameSearch = ko.observable('');
	self.sectionTitleSearch = ko.observable('');
	self.subjectTitleSearch = ko.observable('');

	self.filteredRecords = ko.computed(function() {
		return ko.utils.arrayFilter(self.staffArr(), function(r) {
			return (self.nameSearch().length == 0 || ko.utils.stringStartsWith(r.name().toLowerCase(), self.nameSearch().toLowerCase()) || ko.utils.stringStartsWith(r.sectionStr().toLowerCase(), self.nameSearch()) || ko.utils.stringStartsWith(r.subjectsStr().toLowerCase(), self.nameSearch()))

		});
	});
}

function TeacherStaffVO(data, currentContent) {
	var self = this;
	self.title = ko.observable();
	self.name = ko.observable();
	self.isClassTeacher = ko.observable();
	self.classTitle = ko.observable();
	self.periodPerWeek = ko.observable();
	self.cePeriodPerWeek = ko.observable();
	self.labPeriodPerWeek = ko.observable();

	self.contactNumber = ko.observable();
	self.emailAddress = ko.observable();
	self.section = ko.observableArray([]);

	self.subjectsStr = ko.computed(function() {
		var subjectCtr = "";
		//console.log("subjectCtr")
		var sec = ko.utils.arrayMap(self.section(), function(sectionItem) {
			//console.log("sectionItem---InsideLoop",sectionItem)
			var sub = ko.utils.arrayMap(sectionItem.subject(), function(subjectItem) {
				if (subjectCtr.indexOf(", " + subjectItem.subjectTitle()) == -1) {
					subjectCtr += ", " + subjectItem.subjectTitle();
					//console.log("subjectCtr---InsideLoop",subjectCtr)
				}

			});

		});

		if (subjectCtr.indexOf(", " == 0)) {
			subjectCtr = subjectCtr.substring(1, subjectCtr.length)
		}

		return subjectCtr;
	}, self);
	self.sectionStr = ko.computed(function() {
		var sectionCtr = "";
		//console.log("subjectCtr")
		var sec = ko.utils.arrayMap(self.section(), function(sectionItem) {
			//console.log("sectionItem---InsideLoop",sectionItem)

			//var sub = ko.utils.arrayMap(sectionItem.subject(), function(subjectItem) {
			if (sectionCtr.indexOf(", " + sectionItem.sectionTitle()) == -1) {
				sectionCtr += ", " + sectionItem.sectionTitle();
				//console.log("subjectCtr---InsideLoop",subjectCtr)
			}

			//});

		});

		if (sectionCtr.indexOf(", " == 0)) {
			sectionCtr = sectionCtr.substring(1, sectionCtr.length)
		}

		return sectionCtr;
	}, self);

	self.allocationStr = ko.computed(function() {
		var allocationCtr = 0;
		ctr = 0;
		var sec = ko.utils.arrayMap(self.section(), function(sectionItem) {
			//console.log("sectionItem---InsideLoop",sectionItem)
			var sub = ko.utils.arrayMap(sectionItem.subject(), function(subjectItem) {
				ctr++
				allocationCtr += Number(subjectItem.allocation());
				//console.log(self.name(),ctr,"allocationCtr---InsideLoop",subjectItem.allocation())

			});
		});
		return allocationCtr;
	}, self);

	self.cache = function() {
	};
	self.update(data, currentContent)

	self.openDetailsDialog = function(item) {
		currentContent(item);
		//console.log("currentContent",currentContent().section())
		var teacherDetailsDialog = $("#teachersDetails").dialog("open");
		teacherDetailsDialog.dialog("option", "position", "center");

	}
	self.closeDetailsDialog = function() {

		$("#teachersDetails").dialog("close");

	}
}

function SectionVO(data) {
	var self = this;
	self.sectionId = ko.observable(data.sectionTitle);
	self.sectionTitle = ko.observable(data.sectionTitle);
	self.subject = ko.observableArray([]);

	var mappedSubjectData = jQuery.map(data.subject, function(item) {
		return new SubjectVO(item)
	});
	self.subject(mappedSubjectData);
}

function SubjectVO(data) {
	var self = this;
	self.subjectId = ko.observable(data.subjectId);
	self.subjectTitle = ko.observable(data.subjectTitle);
	self.periodPerWeek = ko.observable(data.periodPerWeek);
	self.cePeriodPerWeek = ko.observable(data.cePeriodPerWeek);
	self.labPeriodPerWeek = ko.observable(data.labPeriodPerWeek);

	self.allocation = ko.computed(function() {
		var allocationStr = Number(self.cePeriodPerWeek()) + Number(self.labPeriodPerWeek()) + Number(self.periodPerWeek());
		return allocationStr;
		//console.log("allocationStr-----------------",allocationStr)
	}, self);

	self.classDetail = ko.observableArray([]);

	var mappedClassData = jQuery.map(data.classDetail, function(item) {
		return new ClassVO(item)
	});
	self.classDetail(mappedClassData);

}

function ClassVO(data) {
	var self = this;
	self.classId = ko.observable(data.classId);
	self.classTitle = ko.observable(data.classTitle);

}

ko.utils.extend(TeacherStaffVO.prototype, {
	update : function(data, currentContent) {
		this.name(data.name || "");
		this.title(data.title || "");
		this.isClassTeacher(data.isClassTeacher || "");
		this.classTitle(data.classTitle || "");
		// this.sectionTitle(data.sectionTitle || "");
		// this.subjectTitle(data.subjectTitle || "");
		this.contactNumber(data.contactNumber || "");
		this.emailAddress(data.emailAddress || "");
		this.periodPerWeek(data.periodPerWeek || "");
		this.cePeriodPerWeek(data.cePeriodPerWeek || "");
		this.labPeriodPerWeek(data.labPeriodPerWeek || "");
		//console.log("this.title==================>",this.title(),this.isClassTeacher())
		var mappedSectionData = jQuery.map(data.section, function(item) {
			return new SectionVO(item)
		});
		this.section(mappedSectionData);

	},

	acceptItem : function(item) {

	},

	//just throw away the edited item and clear the selected observables
	revertItem : function() {

	}
});

ko.utils.extend(TeacherStaffViewModel.prototype, { });

function academicYearIds(data) {
	var self = this;
	self.aypId = ko.observable(data.aypId);
	self.title = ko.observable(data.title);

}

function jsonIOError(exp) {
	console.log("jsonIOError", exp);
}

//--------------Custom Bindings--------------------

ko.bindingHandlers.triggerUpdate = {
	update : function(element, valueAccessor) {
		ko.utils.unwrapObservable(valueAccessor());
		//need to just access the observable to create the subscription
		$(element).trigger("update");
	}
}

//----------------------HELP INTEGRATION----------------------------------------
var isHelpActive = false;

function showHelp() {
	console.log("-------> showing help dialog");

	if (!isHelpActive) {
		isHelpActive = true;
		helpType = "teacher_utilization";
		var active = "0"//$("#tabs").tabs("option", "active");
		help_scrollPosition = 'teacher_utilization_' + active;

		jQuery(".help").load("/ce-static-testedge/common/html/help.html", function() {
			//scrollTo('ayp_section_'+active);
			console.log('ayp_section_' + active);
		});

	} else {
		isHelpActive = false;
		jQuery(".help").empty();
	}
}

function closeHelpSection() {
	console.log("closing help section");
	isHelpActive = false;
	jQuery(".help").empty();
}

function retrunToAcademicYear(event) {
	location.href = baseUrl.replace("p_p_state=exclusive", "p_p_state=normal") + "getAcademics";
}

